<template>
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="900" top="10px" :close-on-click-modal="false" :close-on-press-escape="false" center>
    <el-tabs @tab-click="handleTabClick" v-model="activeName">
      <el-tab-pane label="基本信息" name="first">
        <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px" class="attraction-form">
          <!-- 基本信息 -->
          <div class="form-section">
            <h3 class="section-title">基本信息</h3>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="标题" prop="title">
                  <el-input v-model="formData.title" placeholder="请输入标题" clearable />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="副标题" prop="subTitle">
                  <el-input v-model="formData.subTitle" placeholder="请输入副标题" clearable />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="类型" prop="category">
                  <el-select v-model="formData.category" placeholder="请选择类型" style="width: 100%">
                    <el-option label="科技" value="科技" />
                    <el-option label="生活" value="生活" />
                    <el-option label="财经" value="财经" />
                    <el-option label="娱乐" value="娱乐" />
                    <el-option label="旅游" value="旅游" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="来源" prop="source">
                  <el-input v-model="formData.source" style="width: 100%" placeholder="来源" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="发布状态" prop="isEnabled">
                  <el-select v-model="formData.isEnabled" placeholder="请选择状态" style="width: 100%">
                    <el-option label="启用" :value="true" />
                    <el-option label="禁用" :value="false" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="浏览次数" prop="viewCount">
                  <el-input v-model="formData.viewCount" placeholder="请输入浏览次数" clearable />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="点赞数" prop="viewCount">
                  <el-input v-model="formData.likeCount" placeholder="请输入点赞数" clearable />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="作者" prop="author">
                  <el-input v-model="formData.author" placeholder="请输入作者" clearable />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="发布时间" prop="publishTime">
                  <el-date-picker v-model="formData.publishTime" type="datetime" placeholder="选择发布时间" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <!-- 描述信息 -->
          <div class="form-section">
            <h3 class="section-title">资讯摘要</h3>
            <el-form-item label="资讯摘要" prop="summary">
              <el-input v-model="formData.summary" type="textarea" :rows="4" placeholder="请输入摘要" maxlength="500" show-word-limit />
            </el-form-item>
          </div>

          <!-- 图片管理 -->
          <div class="form-section">
            <h3 class="section-title">封面管理</h3>
            <el-form-item label="封面">
              <div class="image-upload-container">
                <el-upload v-model:file-list="imageFileList" :headers="fileHeader" :action="formAction" :limit="1" :on-success="handleImageUpload" list-type="picture-card" :auto-upload="true" :on-preview="handlePictureCardPreview" :on-remove="handleRemove">
                  <el-icon><Plus /></el-icon>
                </el-upload>
              </div>
            </el-form-item>
            <el-form-item label="">
              <div class="upload-tip">
                <el-text size="small" type="info"> 支持 jpg、png、gif 格式，单张图片不超过 2MB，最多上传 5 张 </el-text>
              </div>
            </el-form-item>
          </div>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="文章内容" name="detail">
        <div class="editor">
          <div id="editToolbar"></div>
          <div id="editContainer"></div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="Html内容" name="htmlContent">
        <el-input v-model="formData.content" :rows="30" type="textarea" placeholder="Please input" />
      </el-tab-pane>
    </el-tabs>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" size="large" @click="submitForm" :loading="submitting"> {{ editMode ? '保存' : '发布资讯' }} </el-button>
        <el-button size="large" @click="() => (dialogVisible = false)">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, shallowRef, onBeforeUnmount, onMounted, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { TabsPaneContext } from 'element-plus'

import '@wangeditor/editor/dist/css/style.css'
import { createEditor, createToolbar } from '@wangeditor/editor'
import type { IEditorConfig } from '@wangeditor/editor'

import { Plus } from '@element-plus/icons-vue'
import http from '@/apis/news'
import type { FormInstance, FormRules, UploadFile, UploadUserFile, UploadProps } from 'element-plus'
import { useUserStore } from '@/stores/user'

const host = import.meta.env.VITE_BASE_URL
const dialogTitle = ref('新增数据')
const userStore = useUserStore()
const submitting = ref(false)

const activeName = ref('detail')

type InsertFnType = (url: string, alt: string, href: string) => void
const editorConfig: Partial<IEditorConfig> = {
  MENU_CONF: {
    codeSelectLang: [
      { text: 'CSS', value: 'css' },
      { text: 'HTML', value: 'html' },
      { text: 'XML', value: 'xml' }
    ],
    uploadImage: {
      server: host + '/api/sysFile/uploadFile',
      fieldName: 'file',
      base64LimitSize: 5 * 1024, // 小于该值就插入 base64 格式（而不上传），默认为 0
      meta: {
        path: 'news'
      },
      // 自定义增加 http  header
      headers: {
        Authorization: 'Bearer ' + localStorage.getItem('token')
      },
      onSuccess(file: File, res: any) {
        // TS 语法
        // onSuccess(file, res) {          // JS 语法
        // console.log(`${file.name} 上传成功`, res)
      },
      // 自定义插入图片
      customInsert(res: any, insertFn: InsertFnType) {
        // res 即服务端的返回结果
        let { code, message, result } = res
        if (code != 200) {
          ElMessage.error(message)
          return
        }
        let url = host + '/' + result.url
        // console.log(res)
        let [alt, href] = [result.fileName, url]
        // console.log(url, alt, href)
        // 从 res 中找到 url alt href ，然后插入图片
        insertFn(url, alt, href)
      },
      // 上传错误，或者触发 timeout 超时
      onError(file: File, err: any, res: any) {
        console.log(`${file.name} 上传出错`, err, res)
        ElMessage.error(`${file.name} 上传出错`)
      }
    }
  }
}

let editor: any = null

onBeforeUnmount(() => {
  console.log('remove editor ')
  editor && editor.destroy()
})

const handleCreateEditor = (html: string) => {
  if (editor) {
    editor.setHtml(html)
    return
  }
  // 创建编辑器
  editor = createEditor({
    selector: '#editContainer',
    html: html,
    config: editorConfig,
    mode: 'default' // or 'simple'
  })
  // 创建工具栏
  const toolbar = createToolbar({
    editor,
    selector: '#editToolbar'
  })

  if (window.hasOwnProperty('editor')) {
    return
  }
  Object.defineProperty(window, 'editor', {
    get() {
      return editor
    }
  })
  // console.log(editor)
}

const handleTabClick = (tab: TabsPaneContext, event: Event) => {
  formData.value.content = editor.getHtml()
}

const formAction = ref(host + '/api/sysFile/uploadFile')
const fileHeader = ref({
  Authorization: 'Bearer ' + localStorage.getItem('token')
})

// 响应式数据
const formRef = ref<FormInstance>()
const dialogVisible = ref(false)
const dialogImageUrl = ref('')

// 表单数据
const formData = ref({
  author: '', // 作者
  category: '', // 分类
  content: '', // 资讯内容
  cover: '', // 封面图地址
  isEnabled: true, // 是否启用
  isPinned: false, // 是否置顶
  likeCount: 0, // 点赞数
  publishTime: '', // 发布时间
  source: '', // 来源
  subTitle: '', // 副标题
  summary: '', // 摘要
  title: '', // 资讯标题
  viewCount: 0 // 浏览次数
})

// 表单验证规则
const rules: FormRules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 2, max: 50, message: '标题长度在 2 到 50 个字符', trigger: 'blur' }
  ]
}

const imageFileList = ref<UploadFile[]>([])

const handleImageUpload = (response: any) => {
  // console.log('Logo上传结果:', response)
  let { code, message, result } = response
  if (code === 200) {
    let url = `${host}/${result.url}`
    formData.value.cover = url
    ElMessage.success('上传成功')
    // console.log('上传成功', url)
  } else {
    ElMessage.error('上传失败: ' + response.message)
  }
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  const index = imageFileList.value.findIndex((item) => item.uid === uploadFile.uid)
  if (index > -1) {
    formData.value.cover = ''
    imageFileList.value.splice(index, 1)
  }
  // console.log(uploadFile, uploadFiles)
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitting.value = true

    // 构造提交数据
    let submitData = {
      ...formData.value
    }
    submitData.content = editor.getHtml()
    if (activeName.value == 'htmlContent') {
      submitData.content = formData.value.content
      console.log(`提交文本内容`)
    }
    if (editMode.value) {
      submitUpdate(submitData)
    } else {
      submitCreate(submitData)
    }
  } catch (error) {
    ElMessage.error('请检查表单填写是否完整')
  } finally {
    submitting.value = false
  }
}

const submitCreate = (submitData: any) => {
  // API调用
  http
    .create(submitData)
    .then((response) => {
      let { code, message } = response.data
      if (code != 200) {
        ElMessage.error(message)
        return
      }
      ElMessage.success('发布成功！')
      dialogVisible.value = false
      emit('create', submitData)
    })
    .catch(() => {
      ElMessage.error('发布失败，请稍后重试')
    })
}
const submitUpdate = (submitData: any) => {
  let keys = ['updateTime', 'updateUserId', 'updateUserName', 'userId']
  keys.forEach((t) => delete submitData[t])
  submitData.status = submitData.status ?? 100
  http
    .update(submitData)
    .then((response) => {
      let { code, message } = response.data
      if (code != 200) {
        ElMessage.error(message)
        return
      }
      ElMessage.success('更新成功！')
      dialogVisible.value = false
      emit('update', submitData)
    })
    .catch(() => {
      ElMessage.error('更新失败，请稍后重试')
    })
}

const emit = defineEmits(['update', 'create'])
const editMode = ref(false)
const handleCreate = () => {
  dialogVisible.value = true
  dialogTitle.value = '新增数据'
  editMode.value = false
  imageFileList.value = []
  formData.value = {
    author: '', // 作者
    category: '', // 分类
    content: '', // 资讯内容
    cover: '', // 封面图地址
    isEnabled: true, // 是否启用
    isPinned: false, // 是否置顶
    likeCount: 10, // 点赞数
    publishTime: '2025-08-01 00:00:00', // 发布时间
    source: '昆明市东川区人民政府', // 来源
    subTitle: '', // 副标题
    summary: '', // 摘要
    title: '', // 资讯标题
    viewCount: 12 // 浏览次数
  }
  nextTick(() => {
    handleCreateEditor('')
  })
}
const handleModify = (obj: any) => {
  dialogVisible.value = true
  formData.value = { ...obj }
  editMode.value = true
  dialogTitle.value = '编辑数据'
  imageFileList.value = []

  nextTick(() => {
    handleCreateEditor(obj.content)
    console.log(obj.content)
  })
  if (!obj.cover) {
    return
  }
  imageFileList.value.push({ url: obj.cover, uid: 100, name: 'file_100', status: 'success' })
}

defineExpose({
  handleCreate,
  handleModify
})
</script>
<style>
.form-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.form-card {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  text-align: center;
}

.card-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.card-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.job-form {
  display: flex;
  flex-wrap: wrap;
}

.form-section {
  margin: 10px 10px;
  flex: 1 1;
  min-width: 400px;
  border-bottom: 1px solid #f0f0f0;
}

.form-section:last-child {
  border-bottom: none;
}

.section-title {
  margin: 0 0 20px 0;
  color: #409eff;
  font-size: 16px;
  font-weight: 600;
  padding-left: 8px;
  border-left: 3px solid #409eff;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
  margin-bottom: 12px;
}

.tags-input {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.tag-item {
  margin: 0;
}

.tag-input {
  width: 120px;
}

.preset-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
}

.submit-section {
  padding: 20px 0px;
  display: flex;
  justify-content: center;
}

.submit-section .el-button {
  margin: 0 8px;
  min-width: 120px;
}
.editor {
  height: auto;
  border: 1px solid #ccc;
}
#editToolbar {
  height: auto;
}
#editContainer {
  height: 50vh;
}
</style>
